package cn.wuyu.baselibrary.base;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.gyf.immersionbar.ImmersionBar;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;

import cn.wuyu.baselibrary.R;
import cn.wuyu.baselibrary.app.SettingConfig;
import cn.wuyu.baselibrary.utils.AppUtil;
import cn.wuyu.baselibrary.utils.DeviceUtil;
import cn.wuyu.baselibrary.utils.KeyboardUtils;
import cn.wuyu.baselibrary.utils.ThemeUtil;
import cn.wuyu.baselibrary.widget.LoadingLayout;
import cn.wuyu.baselibrary.widget.LoadingView;
import cn.wuyu.baselibrary.widget.WuYuLoadingDialog;

/**
 * author : xuzongmeng
 * date   : 2019/2/19.
 * desc   : 描述
 */

public abstract class TestBaseActivity extends AppCompatActivity {

    protected final String TAG = this.getClass().getSimpleName();
    public Context mContext;
    public Toolbar toolBar;
    public LayoutInflater mInflater;
    protected FrameLayout mContainer;
    private TextView tvToolbaerTitle;
    private LoadingLayout mLoadingLayout;
    //	private ActivityBaseLayoutBinding baseBinding;
    /*沉浸栏方案*/
    protected ImmersionBar mImmersionBar;
    /**
     * 带文字提示的加载弹窗
     */
    private WuYuLoadingDialog loadingDialog;

    private String currentClassName = "BaseCommonActivity";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        ThemeUtil.setTheme(this);
        super.onCreate(savedInstanceState);
        int resID = getLayoutID();
        if (resID != 0) {
//			BackgroundLibrary.inject(this);
            setContentView(R.layout.activity_base_layout);
            mContext = this;
            currentClassName = this.getClass().getSimpleName();
            initBaseView();
            String toolBarTitle = getToolBarTitle();
            if (isUseEventBus()) {
                EventBus.getDefault().register(this);
            }
            if (!TextUtils.isEmpty(toolBarTitle)) {
                tvToolbaerTitle.setText(toolBarTitle);
            } else {
                toolBar.setVisibility(View.GONE);
                findViewById(R.id.cardView).setVisibility(View.GONE);
                findViewById(R.id.viewBottom).setVisibility(View.GONE);
            }
            if (isImmersionBarEnabled()) {
                initImmersionBar();
            }
            mContainer.addView(mInflater.inflate(resID, null));
            initView(savedInstanceState);
            AppUtil.getInstance().addActivity(this);
            initData();
            initListener();
        }

    }


    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (isImmersionBarEnabled()) {
            ImmersionBar.with(this).init();
        }
    }

    /**
     * 是否允许沉浸栏
     */
    protected boolean isImmersionBarEnabled() {
        return false;
    }

    /**
     * 初始化沉浸栏
     */
    protected void initImmersionBar() {
//		int attrColor = ResUtils.getAttrColor(R.attr.theme_col);
        ImmersionBar.with(this)
                .titleBar(toolBar)
                .statusBarColor(SettingConfig.isDarkMode() ? R.color.black_theme_col : R.color.white_theme_col)
                .statusBarDarkFont(true)
                .init();
    }

    /**
     * 初始化基类的View
     */
    private void initBaseView() {
        mInflater = LayoutInflater.from(this);
        toolBar = findViewById(R.id.toolbar_base);
        toolBar.setTitle("");
//		String toolBarTitle = getToolBarTitle();
//		if (!TextUtils.isEmpty(toolBarTitle)) {
//			toolBar.setTitle(toolBarTitle);
//		} else {
//			toolBar.setTitle("");
//		}
        setSupportActionBar(toolBar);
        tvToolbaerTitle = findViewById(R.id.tv_base_toolbar_title);
        mLoadingLayout = findViewById(R.id.loadinglayout_base);
        mContainer = findViewById(R.id.fl_content_view);
        mLoadingLayout.setOnReloadListener(v -> {
            showLoading();
            onReLoadData();
        });
        toolBar.setNavigationOnClickListener(view -> {
//			if (KeyboardUtils.isSoftInputVisible(this)){
//				KeyboardUtils.hideSoftInput(this);
//			}
//			if (onOptionNavigation(view))
//			onOptionNavigation(view);
//			try {
//				Method[] declaredMethods = aClass.getDeclaredMethod();
//				declaredMethods.equals()
//			} catch (ClassNotFoundException e) {
//				e.printStackTrace();
//			}
            KeyboardUtils.hideSoftInput(this);
            finish();
        });
    }
    /**
     * 初始化子类数据
     */
    public void onOptionNavigation(View view) {

    }

    /*自定义的一些操作*/
    public void onCreateCustomToolBar(Toolbar toolbar) {
        toolbar.setContentInsetsRelative(0, 0);
    }

    /**
     * 获取子Layout
     */
    protected abstract int getLayoutID();

    /**
     * 设置导航栏标题
     */
    protected String getToolBarTitle() {
        return null;
    }

    /**
     * 初始化子View
     */
    protected void initView(Bundle savedInstanceState) {
    }

    /**
     * 初始化子类数据
     */
    public void initData() {
    }

    /**
     * 添加事件监听
     */
    protected void initListener() {
    }

    /**
     * 重新加载数据   当子类需要时 可以重载此方法
     */
    public void onReLoadData() {
    }

    /**
     * 是否使用 EventBus
     */
    public Boolean isUseEventBus() {
        return false;
    }


    private void closeLoadingView() {
        if (mLoadingView != null) {
            mLoadingView.stopAnim();
        }
    }


    /**
     * 显示加载中 代码形式
     */
    private LoadingView mLoadingView = null;

    public void showLoading() {
        if (DeviceUtil.isConnectNet(this)) {
            LoadingView loadingView = new LoadingView(this, "正在加载中....");
            loadingView.startAnim();
            mLoadingLayout.setLoadingPage(loadingView.getLoadingView());
            mLoadingLayout.setStatus(LoadingLayout.Loading);
            Log.d(TAG, "基类联网了");
        } else {
            mLoadingLayout.setStatus(LoadingLayout.No_Network);
            Log.d(TAG, "基类没有联网");
        }
    }

    /**
     * 显示加载中
     */
    public void showLoading(String msg) {
        if (DeviceUtil.isConnectNet(this)) {
            mLoadingLayout.setStatus(LoadingLayout.Loading);
            mLoadingLayout.setLoadingText(msg);
            Log.d(TAG, "基类联网了");
        } else {
            mLoadingLayout.setStatus(LoadingLayout.No_Network);
//            ToastUtil.showToast("联网失败，请检测网络后重试");
            Log.d(TAG, "基类没有联网");
        }

    }


    /*=========================================================================================*/

    /**
     * 当项目不满足需时 可传入自己LayoutID，显示不同的内容视图 方便扩展
     * （根据用户自定义的View或者LayoutID）
     * 这种方式是让LoadingLayout中滴容器去加载View或者Layout
     */
    public void showContent(int resId) {
        if (mContainer.getChildAt(0) != null) {
            mContainer.removeViewAt(0);
        }
        mContainer.addView(mInflater.inflate(resId, null));
    }
    public void showContent(View view) {
        if (mContainer.getChildAt(0) != null) {
            mContainer.removeViewAt(0);
        }
        mContainer.addView(view);
    }

    /**
     * 显示内容视图
     */
    public void showContent() {
        mLoadingLayout.setStatus(LoadingLayout.Success);
        closeLoadingView();

    }

    /**
     * 显示空数据 ，暂时没有数据
     */

    public void showEmpty() {
        mLoadingLayout.setStatus(LoadingLayout.Empty);
        closeLoadingView();
    }

    /**
     * 显示空数据 ，暂时没有数据
     */

    public void showEmpty(String text) {
        mLoadingLayout.setStatus(LoadingLayout.Empty);
        mLoadingLayout.setEmptyText(text);
        closeLoadingView();
    }

    /**
     * 显示空数据 ，暂时没有数据
     */

    public void showEmpty(String hitMsg, int imageRes) {
        mLoadingLayout.setStatus(LoadingLayout.Empty);
        mLoadingLayout.setEmptyText(hitMsg);
        mLoadingLayout.setEmptyImage(imageRes);
        closeLoadingView();

    }

    /**
     * 显示页面错误
     */
    public void showError() {
        mLoadingLayout.setStatus(LoadingLayout.Error);
        closeLoadingView();
    }

    /**
     * 显示页面错误
     */
    public void showError(String btnMsg) {
        mLoadingLayout.setStatus(LoadingLayout.Error);
        mLoadingLayout.setReloadButtonText(btnMsg);
        closeLoadingView();

    }

    /**
     * 显示页面错误
     */
    public void showError(String btnMsg, String hitMsg) {
        mLoadingLayout.setStatus(LoadingLayout.Error);
        mLoadingLayout.setErrorText(hitMsg);
        mLoadingLayout.setReloadButtonText(btnMsg);
        closeLoadingView();


    }

    /**
     * 显示页面错误
     */
    public void showError(String text, int imageRes) {
        mLoadingLayout.setStatus(LoadingLayout.Error);
        mLoadingLayout.setErrorText(text);
        mLoadingLayout.setErrorImage(imageRes);
        closeLoadingView();

    }


    /**
     * 显示没有网络的情况
     */
    public void showNoNetwork() {
        mLoadingLayout.setStatus(LoadingLayout.No_Network);
        closeLoadingView();
    }

    /**
     * 显示加载弹窗
     */
    public void showLoadingDialog(String message) {
        if (loadingDialog != null && loadingDialog.getDialog() != null && loadingDialog.getDialog().isShowing()) {
            loadingDialog.dismiss();
            loadingDialog.stopAnim();
            return;
        }
        if (loadingDialog != null && loadingDialog.getDialog() != null && !loadingDialog.getDialog().isShowing()) {
            loadingDialog.setMessage(message);
            loadingDialog.startAnim();
            loadingDialog.show(getSupportFragmentManager(), "loadingDialog");
            return;
        }
        if (loadingDialog == null || loadingDialog.getDialog() == null) {
            loadingDialog = new WuYuLoadingDialog();
            loadingDialog.setMessage(message);
            loadingDialog.startAnim();
            loadingDialog.show(getSupportFragmentManager(), "loadingDialog");
        }
    }


    /**
     * 显示加载弹窗
     */
    public void showLoadingDialog() {
        showLoadingDialog("加载中");
    }

    /**
     * 关闭加载弹窗
     */
    public void closeLoadingDialog() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
            loadingDialog.stopAnim();
        }
    }


    /**
     * 是否点击了多次 小于1秒当作是一次点击了
     **/
    private long curClickTimeMillis = 0;

    protected boolean isMultiplicationClick() {
        if (curClickTimeMillis == 0) {
            curClickTimeMillis = System.currentTimeMillis();
            return false;
        }
        boolean rs = System.currentTimeMillis() - curClickTimeMillis < 3000;
        curClickTimeMillis = System.currentTimeMillis();
        return rs;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (isUseEventBus()) {
            EventBus.getDefault().unregister(this);
        }
//        ImmersionBar.with(this).destroy(); //必须调用该方法，防止内存泄漏
//        if (mImmersionBar != null)
//            mImmersionBar.destroy();
        AppUtil.getInstance().finishActivity(this);
    }

    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(currentClassName); //统计页面
        MobclickAgent.onResume(this); //统计时长
    }

    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(currentClassName);//统计页面
        MobclickAgent.onPause(this); //统计时长
    }

    /**
     * 禁止app字体使用系统字体
     */
    @SuppressLint("ObsoleteSdkInt")
    @SuppressWarnings("deprecation")
    @Override
    public Resources getResources() {
        Resources resources = super.getResources();
        Configuration newConfig = resources.getConfiguration();
        DisplayMetrics displayMetrics = resources.getDisplayMetrics();
        if (resources != null && newConfig.fontScale != 1) {
            newConfig.fontScale = 1;
            if (Build.VERSION.SDK_INT >= 17) {
                Context configurationContext = createConfigurationContext(newConfig);
                resources = configurationContext.getResources();
                displayMetrics.scaledDensity = displayMetrics.density * newConfig.fontScale;
            } else {
                resources.updateConfiguration(newConfig, displayMetrics);
            }
        }
        return resources;
    }


}
